<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/login.css">
</head>
<body>
    <div class="photo">
        <img src="https://pic.mdcdn.cn/h5/pic/201704/1402b48b1915.jpg@100Q.jpg" alt="">
    </div>
    <div class="login">
        <form>
            <span class="error">该用户名以被占用, 请更换后重试! ^_^</span>
            <label>
                用&nbsp;&nbsp;&nbsp;&nbsp;户&nbsp;&nbsp; ：<input type="text" class="username">
            </label>
            <label>
                  密&nbsp;&nbsp;&nbsp;&nbsp;码&nbsp;&nbsp; ：<input type="text" class="password">
            </label>
            <label>
                确认密码 ：<input type="text" class="rpassword">
          </label>
          <label>
            昵&nbsp;&nbsp;&nbsp;&nbsp;称&nbsp;&nbsp; : <input class="nickname" type="text">
          </label>
            <p>已有账号,<a href="./login.html">前往登录</a></p>
        <button>注册</button>
        </form>
    </div>
    <script src="../js/utils.js"></script>
    <script>
       const form = document.querySelector('form')
const nameInp = document.querySelector('.username')
const pwdInp = document.querySelector('.password')
const rpwdInp = document.querySelector('.rpassword')
const nickInp = document.querySelector('.nickname')
const errBox = document.querySelector('.error')


// 1. 给 form 添加表单提交事件
form.addEventListener('submit', e => {
  e = e || window.event
  try { e.preventDefault() } catch (err) { e.returnValue = false }

  // 2. 拿到你填写的所有内容
  const info = {
    username: nameInp.value,
    password: pwdInp.value,
    rpassword: rpwdInp.value,
    nickname: nickInp.value
  }

  // 3. 非空验证
  // 遍历
  for (let key in info) {
    if (!info[key]) return alert('请完整填写表单')
  }
  // 3-2. 验证 密码 和 重复密码 一致
  if (info.password !== info.rpassword) return alert('两次密码不一致')

  // 4. 发送请求
  // 使用我们封装好的 ajax 方法来发送
  // 需要传递参数, 'username=Jack&password=123465&rpassword=123456&nickname=asdasda'
  ajax({
    url: 'http://localhost:8081/xte/server/register.php',
    method: 'POST',
    data: querystringify(info),
    dataType: 'json',
    success: function (res) {
      // 5. 根据结果进行不同的操作
      if (res.code === 0) {
        errBox.classList.add('active')
        return
      }

      // 代码到这里说明注册成功了
      window.alert('注册成功, 点击确定跳转到登录页')
      window.location.href = './login.html'
    }
  })
})
    </script>
</body>
</html>